package com.baitiaojun.system.admin.service.tenant.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baitiaojun.common.enums.impl.OperatorTypeEnums;
import com.baitiaojun.common.enums.impl.ServiceExpEnums;
import com.baitiaojun.common.enums.impl.ServiceTypeEnums;
import com.baitiaojun.common.enums.impl.TenantStatusEnums;
import com.baitiaojun.common.exception.ServiceException;
import com.baitiaojun.common.utils.asserts.AssertUtils;
import com.baitiaojun.common.utils.date.DateTimeUtils;
import com.baitiaojun.log.core.annotation.OperLog;
import com.baitiaojun.system.admin.controller.tenant.req.TenantRegisterReq;
import com.baitiaojun.system.admin.helper.CaptchaHelper;
import com.baitiaojun.system.admin.pojo.DbConfigDO;
import com.baitiaojun.system.admin.service.config.DbConfigService;
import com.baitiaojun.system.admin.service.tenant.TenantService;
import com.baitiaojun.tenant.dto.MasterTenantDTO;
import com.baitiaojun.tenant.dto.TenantDTO;
import com.baitiaojun.tenant.facroty.DBLoaderFactory;
import com.baitiaojun.tenant.loader.DataSourceLoader;
import com.baitiaojun.tenant.loader.impl.MySQLDatasourceLoader;
import com.baitiaojun.tenant.service.MasterTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

@Service
public class TenantServiceImpl implements TenantService {

    @Autowired
    private MasterTenantService masterTenantService;

    @Autowired
    private DbConfigService dbConfigService;

    @Autowired
    private CaptchaHelper captchaHelper;

    @OperLog(title = "TenantServiceImpl.tenantRegister",
            businessTypeEnums = ServiceTypeEnums.INSERT,
            operatorTypeEnums = OperatorTypeEnums.MANAGE)
    @Override
    public void tenantRegister(TenantRegisterReq registerReq) {
        //验证码校验
        captchaHelper.validateCaptcha(registerReq.getCaptchaId(), registerReq.getCaptcha());

        //查询该租户是否已存在
        MasterTenantDTO masterTenant = masterTenantService.queryTenant(registerReq.getTenant());
        if (masterTenant != null) {
            throw new ServiceException(ServiceExpEnums.EXP_EXISTS_TENANT);
        }

        //查询默认数据库配置是否存在
        DbConfigDO dbConfigDO = dbConfigService.queryOne("default");
        if (dbConfigDO == null) {
            throw new ServiceException(ServiceExpEnums.EXP_BAD_DEFAULT_DB_CONFIG);
        }

        //进行租户数据库初始化
        DataSourceLoader dbLoader = DBLoaderFactory.getDBLoader(MySQLDatasourceLoader.class);
        TenantDTO tenantDTO = BeanUtil.copyProperties(registerReq, TenantDTO.class);
        tenantDTO.setDriver(dbConfigDO.getDriver());
        tenantDTO.setUrl(dbConfigDO.getUrl());
        tenantDTO.setUsername(dbConfigDO.getUsername());
        tenantDTO.setPassword(dbConfigDO.getPassword());
        String dbName = dbLoader.initDB(tenantDTO);

        //添加租户
        MasterTenantDTO masterTenantDTO = BeanUtil.copyProperties(registerReq, MasterTenantDTO.class);
        masterTenantDTO.setDriver(dbConfigDO.getDriver());
        String url = dbConfigDO.getUrl() + "/" + dbName + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
        masterTenantDTO.setUrl(url);
        masterTenantDTO.setUsername(dbConfigDO.getUsername());
        masterTenantDTO.setPassword(dbConfigDO.getPassword());
        masterTenantDTO.setDatabaseName(dbName);
        masterTenantDTO.setStatus(String.valueOf(TenantStatusEnums.NORMAL.getCode()));
        //默认过期时间是当前时间+1个月
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        String dateTime = DateTimeUtils.getDateTime(calendar.getTime());
        masterTenantDTO.setExpirationDate(DateTimeUtils.parseDate(dateTime));
        boolean tenant = masterTenantService.createTenant(masterTenantDTO);
        AssertUtils.isTrue(tenant, ServiceExpEnums.EXP_BAD_INIT_TENANT);
    }
}
